package main

import (
	"cow_golang/shared_mod/tcplib"
	"fmt"
	"io"
	"net"
	"time"
)

func main() {
	fmt.Println("Client Test ... start")
	time.Sleep(3 * time.Second)

	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		fmt.Println("client start err:", err)
		return
	}

	for {
		// 封包
		dp := tcplib.NewMessagePack()
		msg, _ := dp.Pack(tcplib.NewMessage(1, []byte("ping")))
		// 发消息
		_, err := conn.Write(msg)
		if err != nil {
			fmt.Println("client Write err:", err)
			return
		}
		//读取回应
		//读取包头
		headData := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, headData); err != nil {
			fmt.Println("Session Read head Error:", err)
			break
		}
		// 解析包头，获得消息id和数据长度
		msgHead, err := dp.UnPack(headData)
		if err != nil {
			fmt.Println("Session unpack Error:", err)
			return
		}
		// 读取数据
		if msgHead.GetDataLen() > 0 {
			//创建读取数据的buff
			msg := msgHead.(*tcplib.Message)
			msg.Data = make([]byte, msg.GetDataLen())
			if _, err := io.ReadFull(conn, msg.Data); err != nil {
				fmt.Println("Session Read data Error:", err)
				return
			}
			fmt.Println("recv msg id:", msg.GetMsgId(),
				" len:", msg.GetDataLen(),
				" data:", string(msg.Data))
		}

		time.Sleep(1 * time.Second)
	}
}
